package com.heyqing.topic.Intersect_0350;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * ClassName:Intersect
 * Package:com.heyqing.topic.Intersect_0350
 * Description:
 *
 * @Date:2024/9/27
 * @Author:Heyqing
 */
public class Intersect {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Long> num1Map = Arrays.stream(nums1).boxed().collect(Collectors.groupingBy(
                Function.identity(),
                Collectors.counting()
        ));
        Map<Integer, Long> num2Map = Arrays.stream(nums2).boxed().collect(Collectors.groupingBy(
                Function.identity(),
                Collectors.counting()
        ));
        List<Integer> resultList = new ArrayList<>();
        for (int i = 0; i < nums1.length; i++) {
            int flag = nums1[i];
            Long loop1 = num1Map.get(flag);
            Long loop2 = num2Map.get(flag);
            if (Objects.isNull(loop1) || Objects.isNull(loop2)) continue;
            for (int j = 0; j < Math.min(loop1, loop2); j++) {
                resultList.add(flag);
            }
            num1Map.remove(flag);
            num2Map.remove(flag);
        }
        return resultList.stream().mapToInt(Integer::intValue).toArray();
    }
}
